TOP_DIR = $(shell realpath ../..)

CC = gcc
LD = gcc

OS = $(shell uname)

LITTLEFS_DIR = $(TOP_DIR)/system/kernel/fs/littlefs

SRC = $(LITTLEFS_DIR)/lfs.c \
	  $(LITTLEFS_DIR)/lfs_util.c \
	  ./mklfs.c

INC = $(LITTLEFS_DIR)

CFLAGS = -std=gnu11 -Wall $(foreach i, $(INC), -I$(i))

ifeq ($(OS), Darwin)
LD_FLAGS = -Wl,-map,$(TARGET_MAP)
else
LD_FLAGS = -Wl,-Map=$(TARGET_MAP)
endif

BUILD_DIR = $(TOP_DIR)/tools/mklfs/build

TARGET_DIR = $(BUILD_DIR)/bin
OBJ_DIR = $(BUILD_DIR)/obj

TARGET = $(TARGET_DIR)/mklfs
TARGET_MAP = $(TARGET_DIR)/mklfs.map

c2o = $(addprefix $(OBJ_DIR)/, $(notdir $(1:.c=.o)))

OBJS = $(call c2o, $(SRC))

DEPS = $(OBJS:%.o=%.d)

define compile
$(call c2o, $(1)): $(1)
	@echo CC $(call c2o, $(1))
	@mkdir -p $(dir $(call c2o, $(1)))
	@$(CC) $(CFLAGS) -c $(1) -o $(call c2o, $(1)) -MMD -MF $(call c2o, $(1:.c=.d)) -MP
endef

$(TARGET): $(OBJS)
	@echo LD $@
	@mkdir -p $(dir $@)
	@$(LD) $^ -o $@ $(LD_FLAGS)

$(foreach c, $(SRC), $(eval $(call compile, $(c))))

$(foreach d, $(DEPS), $(eval -include $(d)))
